package cn.xiaochao.mapper;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

import cn.xiaochao.zebra.common.OwnEnv;
import cn.xiaochao.zebra.common.ZKConnectRunner;
import rpc.domain.FileSplit;
import rpc.domain.HttpAppHost;

public class MapperRunner2 implements Runnable {
	public void run() {
		while(true){
			try {
				//保存的是处理后的信息
				Map<CharSequence,HttpAppHost> map = new HashMap<>();
				FileSplit split = OwnEnv.getSpiltQueue().take();
				//将当前的一级引擎改为busy
//				ZKConnectRunner.setBusy();
				//获取未切块的文件
				File file = new File(split.getPath().toString());
				long start = split.getStart();
				long end = start+split.getLength();
				//有可能切块后，考虑到不一定都是从行首、行尾切,
				//所以需要追溯start和end，均采用向前追溯的方式
				//start不为0需要进行追溯
				FileChannel fc = new FileInputStream(
						file).getChannel();
				if(start!=0){
					long headPosition = start;
					while(true){
						ByteBuffer buf = ByteBuffer.allocate(1);
						fc.position(headPosition);
						fc.read(buf);
						if("\n".equals(new String(buf.array()))){
							headPosition++;
							start = headPosition;
							break;
						}else{
							headPosition--;
						}
					}
				}
				//end不为文件的结尾
				if(end!=file.length()){
					long endPosition =end;
					while(true){
						ByteBuffer buf = ByteBuffer.allocate(1);
						fc.position(endPosition);
						fc.read(buf);
						if("\n".equals(new String(buf.array()))){
							end = endPosition;
							break;
						}else{
							endPosition--;
						}
					}
				}
				//设置起始位置
				fc.position(start);
				ByteBuffer splitBuf = ByteBuffer.allocate(
						(int)(end-start));
				fc.read(splitBuf);
				//ByteBuffer->BufferedReader
				BufferedReader reader=new BufferedReader(
						new InputStreamReader(
						new ByteArrayInputStream(splitBuf.array())));
				String line = null;
				while((line=reader.readLine())!=null){
					String[] data = line.split("\\|");
					HttpAppHost hah=new HttpAppHost();
					String reportTime=file.getName().split("_")[1];
					hah.setReportTime(reportTime);
					//上网小区的id
					hah.setCellid(data[16]);
					//应用大类
					hah.setAppType(Integer.parseInt(data[22]));
					//应用子类
					hah.setAppSubtype(Integer.parseInt(data[23]));
					//用户ip
					hah.setUserIP(data[26]);
					//用户port
					hah.setUserPort(Integer.parseInt(data[28]));
					//访问的服务ip
					hah.setAppServerIP(data[30]);
					//访问的服务port
					hah.setAppServerPort(Integer.parseInt(data[32]));
					//域名
					hah.setHost(data[58]);
					//业务类型编码
					int appTypeCode=Integer.parseInt(data[18]);
					String transStatus=data[54];
					//--将需要计算的属性，按照业务规则通过辅助信息进行计算后设置到hah中
					//----业务规则1:如果没有小区编号，就将小区编号补齐为000000000
					if(hah.getCellid()==null||hah.getCellid().equals("")){
						hah.setCellid("000000000");
					}
					//----业务规则2:计算尝试次数 - attempts if( App Type Code=103 ) 1
					if(appTypeCode==103){
						hah.setAttempts(1);
					}
					//----业务规则3:接受次数 - accepts if( App Type Code=103 & HTTP/WAP事物状态 in(10,11,...,200,201,202,203,204,205,206,302,304,306) && Wtp中断类型==NULL) then counter++ 1
					if(appTypeCode==103 &&"10,11,12,13,14,15,32,33,34,35,36,37,38,48,49,50,51,52,53,54,55,199,200,201,202,203,204,205 ,206,302,304,306".contains(transStatus)
							&&data[67]==null){
						hah.setAccepts(1);
					}else{
						hah.setAccepts(0);
					}
					if(appTypeCode == 103){
						hah.setTrafficUL(Long.parseLong(data[33]));
						hah.setTrafficDL(Long.parseLong(data[34]));
						hah.setRetranUL(Long.parseLong(data[39]));
						hah.setRetranDL(Long.parseLong(data[40]));
						//业务规则4:传输延时=请求结束-请求起始
						hah.setTransDelay(Long.parseLong(data[20]) -Long.parseLong(data[19]));
					}
					//声明代表一个日志唯一的key
					CharSequence key=hah.getReportTime() + "|" + hah.getAppType() + "|" + hah.getAppSubtype() + "|" + hah.getUserIP() + "|" + hah.getUserPort() + "|" + hah.getAppServerIP() + "|" + hah.getAppServerPort() +"|" + hah.getHost() + "|" + hah.getCellid();
					if(map.containsKey(key)){
						HttpAppHost mapHah=map.get(key);
						mapHah.setAccepts(mapHah.getAccepts()+hah.getAccepts());
						mapHah.setAttempts(mapHah.getAttempts()+hah.getAttempts());
						mapHah.setTrafficUL(mapHah.getTrafficUL()+hah.getTrafficUL());
						mapHah.setTrafficDL(mapHah.getTrafficDL()+hah.getTrafficDL());
						mapHah.setRetranUL(mapHah.getRetranUL()+hah.getRetranUL());
						mapHah.setRetranDL(mapHah.getRetranDL()+hah.getRetranDL());
						mapHah.setTransDelay(mapHah.getTransDelay()+hah.getTransDelay());
						map.put(key, mapHah);
					}else{
						map.put(key,hah);
					}
				}
				System.out.println("切块处理后："+map.size());
				OwnEnv.getMapQueue().add(map);
				//将状态该为free
//				ZKConnectRunner.setFree();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
